/**
 * 语言router
 */

import express from "express";
import { Schema } from "mongoose";
import { addData, findAll, updateData, deleteData } from "../mdb/controlDB";
import { baseResp, langSchematype, langModalname } from "../common";

const router = express.Router();

const langschema = new Schema(langSchematype);

interface ITLangItem {
  _id: any;
  key: string;
  en: string;
  cn: string;
  desc: string;
}

// 查询所有
router.get("/all", async function (req, res) {
  const findBack = (data: ITLangItem[]) => {
    let list: any[] = [];
    if (data && data.length) {
      data.forEach((item) => {
        const { _id, key, en, cn, desc } = item;
        list.push({
          id: _id.toString(),
          key,
          en,
          cn,
          desc,
        });
      });
    }
    res.json(Object.assign({}, baseResp, { data: list }));
  };
  findAll({
    schematype: langschema,
    callback: findBack,
    modalname: langModalname,
  });
});

// 新增数据
router.post("/add", function (req, res) {
  const param = req.body;
  const addback = (data: any) => {
    res.json(Object.assign({}, baseResp, { ...data }));
  };

  addData({
    schematype: langschema,
    callback: addback,
    modalname: langModalname,
    param,
  });
});

// 修改数据
router.post("/update", (req, res) => {
  const param = req.body;

  const editback = (data: any) => {
    res.json(Object.assign({}, baseResp, { data }));
  };
  updateData({
    schematype: langschema,
    callback: editback,
    modalname: langModalname,
    param,
  });
});

// 删除数据
router.post("/delete", (req, res) => {
  const param = req.body;

  const delback = (data: any) => {
    res.json(Object.assign({}, baseResp, { data }));
  };
  deleteData({
    schematype: langschema,
    callback: delback,
    modalname: langModalname,
    param,
  });
});

export default router;
